﻿/**************************************************************
 *
 * 命名空间：Sgr.UPMS.Application.Commands.Menus
 * 创建时间：2025/3/20
 * 描述：删除菜单命令处理器
 *
 **************************************************************/

using MediatR;
using Sgr.Application.Commands;
using Sgr.UPMS.Domain.Menus;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.UPMS.Application.Commands.Menus
{
    /// <summary>
    /// 删除菜单命令处理器
    /// </summary>
    public class DeleteMenuCommandHandler : IRequestHandler<DeleteMenuCommand, CommandResult<bool>>
    {
        private readonly IMenuManage _menuManage;
        private readonly IMenuRepository _menuRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        public DeleteMenuCommandHandler(
            IMenuManage menuManage, IMenuRepository menuRepository)
        {
            _menuManage = menuManage;
            _menuRepository = menuRepository;
        }

        /// <summary>
        /// 处理命令
        /// </summary>
        public async Task<CommandResult<bool>> Handle(DeleteMenuCommand command, CancellationToken cancellationToken)
        {
            // 查找部门实体
            var entity = await _menuRepository.GetAsync(command.Id, cancellationToken);

            // 如果找不到部门，返回NotFound结果
            if (entity == null)
                return CommandResult.NotFound<bool>("未找到指定的菜单");

            // 提交事务
            bool result = await _menuManage.RemoveNodeAsync(entity, command.Cascade, cancellationToken);

            // 验证保存结果
            if (!result)
                return CommandResult.Error<bool>("删除菜单过程中发生错误");

            // 返回成功结果
            return CommandResult.Success(true, "菜单删除成功");
        }
    }
}